package com.xjj.datarources.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xjj.datarources.base.DBContextHandler;
import com.xjj.datarources.base.DataSources;
import com.xjj.datarources.base.DynamicDataSource;
import com.xjj.datarources.dao.DataSourceMapper;
import com.xjj.datarources.service.DBChangeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @name: xjj
 * @date: 2021/5/19 17:25
 */
@Service
public class DBChangeImpl implements DBChangeService {

    @Resource
    private DataSourceMapper mapper;


    @Resource
    private DynamicDataSource dynamicDataSource;

    @Override
    public boolean changeDb(String dataId) {

        DBContextHandler.clearDataSource();
        QueryWrapper<DataSources> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", dataId);
        List<DataSources> list = mapper.selectList(queryWrapper);


        try {
            dynamicDataSource.createDataSourceWithCheck(list.get(0));
            DBContextHandler.setDataSource(list.get(0).getId());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }


        return false;
    }
}
